<template>
  <div class="department-management-container">


    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <div class="search-row">
        <div class="search-item">
          <label>部门名称:</label>
          <el-input v-model="searchForm.departmentName" placeholder="请输入部门名称" clearable @keyup.enter="handleSearch" />
        </div>
        <div class="search-item">
          <label>上级部门:</label>
          <el-select v-model="searchForm.parentId" placeholder="请选择上级部门" clearable style="width: 200px;">
            <el-option v-for="dept in departmentOptions" :key="dept.id" :label="dept.departmentName" :value="dept.id" />
          </el-select>
        </div>
        <div class="search-actions">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
      <div class="action-row">
        <div class="right-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增部门
          </el-button>

        </div>
      </div>
    </div>

    <!-- 部门列表 -->
    <div class="main-content">
      <div class="table-container">
        <el-table :data="departmentList" v-loading="tableLoading" border stripe style="width: 100%">
          
          <el-table-column prop="departmentName" label="部门名称" width="200" />
          <el-table-column prop="departmentCode" label="部门编码" width="150" />
          <el-table-column prop="parentName" label="上级部门" width="150" />
          <el-table-column prop="level" label="层级" width="80" />
          <el-table-column prop="sortOrder" label="排序" width="80" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="addTime" label="创建时间" width="160">
            <template #default="scope">

              {{ moment(scope.row.addTime).format("yyyy-MM-DD HH:mm:ss") }}
            </template>

          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" :type="scope.row.status === 1 ? 'danger' : 'success'"
                @click="handleToggleStatus(scope.row)">
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="departmentFormRef" :model="departmentForm" :rules="departmentFormRules" label-width="100px">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="departmentForm.departmentName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="departmentCode">
          <el-input v-model="departmentForm.departmentCode" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="上级部门" prop="parentId">
          <el-select v-model="departmentForm.parentId" placeholder="请选择上级部门" clearable style="width: 100%;">
            <el-option v-for="dept in departmentOptions" :key="dept.id" :label="dept.departmentName" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="departmentForm.sortOrder" :min="0" :max="999" placeholder="请输入排序值"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="departmentForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="departmentForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Refresh } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import * as departmentApi from '../../api/department'
import moment from 'moment'

// ==================== 接口定义 ====================
/**
 * 部门信息接口
 * 定义部门的基本信息结构
 */
interface Department {
  id: number
  departmentName: string
  departmentCode: string
  parentId: number | null
  parentName?: string
  level: number
  sortOrder: number
  status: number
  remark?: string
  addTime: string
}

/**
 * 搜索表单接口
 * 定义部门搜索的条件
 */
interface SearchForm {
  departmentName: string
  parentId: number | null
}

/**
 * 部门表单接口
 * 定义新增/编辑部门时的表单数据
 */
interface DepartmentForm {
  id?: number
  departmentName: string
  departmentCode: string
  parentId: number | null
  level?: number
  sortOrder: number
  remark?: string
  status: number
  addProp: string
}

/**
 * 分页信息接口
 * 定义分页相关的参数
 */
interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// ==================== 响应式数据 ====================
// 部门列表数据
const departmentList = ref<Department[]>([])
// 部门选项数据（用于下拉选择）
const departmentOptions = ref<Department[]>([])
// 表格加载状态
const tableLoading = ref(false)
// 对话框显示状态
const dialogVisible = ref(false)
// 对话框标题
const dialogTitle = ref('')

// 搜索表单
const searchForm = reactive<SearchForm>({
  departmentName: '',
  parentId: null
})

// 部门表单
const departmentForm = reactive<DepartmentForm>({
  departmentName: '',
  departmentCode: '',
  parentId: null,
  sortOrder: 0,
  remark: '',
  status: 1,
  addProp: ""
})

// 分页信息
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单引用
const departmentFormRef = ref<FormInstance>()

// ==================== 表单验证规则 ====================
/**
 * 部门表单验证规则
 * 定义各个字段的验证条件
 */
const departmentFormRules: FormRules = {
  departmentName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '部门名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  departmentCode: [
    { required: true, message: '请输入部门编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_]+$/, message: '部门编码只能包含大写字母、数字和下划线', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// ==================== 生命周期钩子 ====================
/**
 * 组件挂载时初始化数据
 * 加载部门列表和部门选项
 */
onMounted(() => {
  loadDepartmentList()
  loadDepartmentOptions()
})

// ==================== 数据加载方法 ====================
/**
 * 加载部门列表
 * 根据搜索条件和分页参数获取部门数据
 */
const loadDepartmentList = async () => {
  try {
    tableLoading.value = true
    const response = await departmentApi.getDepartmentList({
      departmentName: searchForm.departmentName,
      parentId: searchForm.parentId,
      page: pagination.currentPage,
      size: pagination.pageSize
    })

    if (response.data.code === 200) {
      departmentList.value = response.data.data.list || []
      pagination.total = response.data.data.count || 0
    } else {
      ElMessage.error(response.data.message || '加载部门列表失败')
    }
  } catch (error) {
    ElMessage.error('加载部门列表失败')
    console.error('加载部门列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

/**
 * 加载部门选项
 * 获取所有部门用于下拉选择
 */
const loadDepartmentOptions = async () => {
  try {
    const response = await departmentApi.getAllDepartments()

    if (response.data.code === 200) {
      departmentOptions.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '加载部门选项失败')
    }
  } catch (error) {
    ElMessage.error('加载部门选项失败')
    console.error('加载部门选项失败:', error)
  }
}

// ==================== 搜索和操作方法 ====================
/**
 * 执行搜索
 * 重置分页并重新加载数据
 */
const handleSearch = () => {
  pagination.currentPage = 1
  loadDepartmentList()
}

/**
 * 重置搜索条件
 * 清空搜索表单并重新加载数据
 */
const resetSearch = () => {
  searchForm.departmentName = ''
  searchForm.parentId = null
  pagination.currentPage = 1
  loadDepartmentList()
}

/**
 * 刷新数据
 * 重新加载当前页面的数据
 */
const refreshData = () => {
  loadDepartmentList()
}

/**
 * 分页大小改变
 * 当用户改变每页显示数量时触发
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadDepartmentList()
}

/**
 * 当前页改变
 * 当用户切换页码时触发
 */
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadDepartmentList()
}

// ==================== 部门操作方法 ====================
/**
 * 新增部门
 * 打开新增部门对话框
 */
const handleAdd = () => {
  dialogTitle.value = '新增部门'
  resetForm()
  dialogVisible.value = true
}

/**
 * 编辑部门
 * 打开编辑部门对话框并填充数据
 */
const handleEdit = (department: Department) => {
  dialogTitle.value = '编辑部门'
  Object.assign(departmentForm, {
    id: department.id,
    departmentName: department.departmentName,
    departmentCode: department.departmentCode,
    parentId: department.parentId,
    level: department.level,
    sortOrder: department.sortOrder,
    remark: department.remark,
    status: department.status,
    addProp: localStorage.getItem("userNickname") || ''
  })
  dialogVisible.value = true
}

/**
 * 切换部门状态
 * 启用或禁用部门
 */
const handleToggleStatus = async (department: Department) => {
  const action = department.status === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}部门 "${department.departmentName}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await departmentApi.toggleDepartmentStatus(department.id, department.status === 1 ? 0 : 1)

    if (response.data.code === 200) {
      ElMessage.success(`${action}部门成功`)
      loadDepartmentList()
    } else {
      ElMessage.error(response.data.message || `${action}部门失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}部门失败`)
      console.error(`${action}部门失败:`, error)
    }
  }
}

/**
 * 删除部门
 * 删除指定部门
 */
const handleDelete = async (department: Department) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除部门 "${department.departmentName}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await departmentApi.deleteDepartment(department.id)

    if (response.data.code === 200) {
      ElMessage.success('删除部门成功')
      loadDepartmentList()
    } else {
      ElMessage.error(response.data.message || '删除部门失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除部门失败')
      console.error('删除部门失败:', error)
    }
  }
}

/**
 * 导出部门数据
 * 导出部门列表到Excel
 */
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
  // TODO: 实现导出功能
}

// ==================== 表单处理方法 ====================
/**
 * 重置表单
 * 清空表单数据
 */
const resetForm = () => {
  Object.assign(departmentForm, {
    id: undefined,
    departmentName: '',
    departmentCode: '',
    parentId: null,
    level: undefined,
    sortOrder: 0,
    remark: '',
    status: 1
  })
  departmentFormRef.value?.clearValidate()
}

/**
 * 提交表单
 * 验证表单并提交数据
 */
const submitForm = async () => {
  if (!departmentFormRef.value) return

  try {
    await departmentFormRef.value.validate()

    let response
    if (departmentForm.id) {
      response = await departmentApi.updateDepartment(departmentForm)
    } else {
      departmentForm.addProp = localStorage.getItem("userNickname") || ''
      response = await departmentApi.createDepartment(departmentForm)
    }

    if (response.data.code === 200) {
      ElMessage.success(departmentForm.id ? '更新部门成功' : '创建部门成功')
      dialogVisible.value = false
      loadDepartmentList()
      loadDepartmentOptions() // 重新加载部门选项
    } else {
      ElMessage.error(response.data.message || '保存部门失败')
    }
  } catch (error) {
    ElMessage.error('保存部门失败')
    console.error('保存部门失败:', error)
  }
}
</script>

<style scoped>
.department-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.search-actions {
  display: flex;
  gap: 10px;
}

.action-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.refresh-icon {
  font-size: 18px;
  color: #409eff;
  cursor: pointer;
  transition: color 0.3s;
}

.refresh-icon:hover {
  color: #66b1ff;
}

.main-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-container {
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>